<?php

class AdminProductIncludeController extends AdminController {

	public function getCreate($id)
	{
		$model = new ProductInclude;
		$products = $model->productIncludes($id);
		$selected_products = $model->selectedProducts($id);
		$data['products'] = $products;

		$product = Product::find($id);
		$data['product'] = $product;

		$this->layout->title = trans('product.create_include');
		$this->layout->content = View::make('admin.product_include.form', $data);
	}

	public function postAdd()
	{
		$result = array('error' => true, 'message' => 'Only accept ajax request!');

		if(Request::ajax())
		{
			$result = array('error' => true, 'message' => 'Something is error!');

			$data['include']  = Input::get('include', 0);
			$data['product']  = Input::get('product', 0);

			if($data['include'] > 0 && $data['product'] > 0)
			{
				$data['quantity'] = 1;

				$model = new ProductInclude;
				$model->saveData($data);

				$result = array('error' => false, 'message' => 'Data is saved');
			}
		}

		return json_encode($result);
	}

	public function postChangeQuantity(){
		$result = array('error' => true, 'message' => 'Only accept ajax request!');

		if(Request::ajax())
		{
			$result   = array('error' => true, 'message' => 'Something is error!');
			
			$id       = Input::get('id', 0);
			$quantity = Input::get('quantity', 1);

			$model           = new ProductInclude;
			$product_include = $model->findOrFail($id);
			$validator       = $model->validator(array('quantity' => $quantity));

			if($product_include !== false && $validator->fails() === false)
			{
				$product_include->quantity = $quantity;
				$product_include->save();

				$result = array('error' => false, 'message' => 'Data is saved');
			}else{
				$result = array('error' => true, 'message' => $model->getValidatorMessage());
			}
		}

		return json_encode($result);
	}

	public function postGet(){
		$result = array('error' => true, 'message' => 'Only accept ajax request!');

		if(Request::ajax())
		{
			$result = array('error' => true, 'message' => 'Something is error!');

			$product  = Input::get('product', 0);

			$model = new ProductInclude;
			$data = $model->selectedProducts($product);

			if(count($data) > 0){
				$result = array('error' => false, 'data' => $data);
			}
		}

		return json_encode($result);
	}

	public function postDelete()
	{
		$error   = true;
		$message = "Only accept ajax request!";

		if(Request::ajax()){
			$id    = Input::get('id', 0);
			
			$model = new ProductInclude;
			$product_include = $model->findOrFail($id);

			$error   = true;
			$message = "product customer not found!";

			if($product_include !== false){
				$product_include->delete();

				$error   = false;
				$message = "data is deleted";
			}
		}

		return json_encode(array('error' => $error, 'message' => array('message' => $message)));
	}
}